<template>
  <div class="config">
    <van-form ref="formRef" @submit="onSubmit">
      <van-cell-group inset>
        <van-field name="clockTime" label="倒计时">
          <template #label>
            刷脸倒计时
          </template>
          <template #input>
            <div class="clock-time-container">
              <span class="clock-time-display">{{ countdownDisplay }}</span>
              <van-button plain type="primary" size="small" @click="resetClockTime" class="reset-button">
                <van-icon name="replay" />
                刷脸时间重置
              </van-button>
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 模式选择 -->
      <!-- <van-cell-group inset>
        <van-field name="selectedTypes" placeholder="请选择模式" :rules="[{ required: true, message: '请选择模式！' }]">
          <template #label>
            <van-icon name="more" style="margin-right: 5px" />模式
          </template>
          <template #input>
            <van-checkbox-group v-model="configForm.selectedTypes" direction="horizontal">
              <van-checkbox name="行程" shape="square" icon-size="14px">行程</van-checkbox>
              <van-checkbox name="城际大厅" shape="square" icon-size="14px">城际</van-checkbox>
              <van-checkbox name="市内大厅" shape="square" icon-size="14px">市内</van-checkbox>
              <van-checkbox name="常用路线" shape="square" icon-size="14px">常用</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
      </van-cell-group> -->

      <!-- 模拟位置 -->
      <van-cell-group inset>
        <van-field v-model="configForm.startGisName" name="startGisName" placeholder="请输入模拟位置"
          :rules="[{ required: true, message: '请输入模拟位置' }]">
          <template #label>
            <van-icon name="location" style="margin-right: 5px" />模拟位置
          </template>
          <template #input>
            <div class="location-input">
              <van-field v-model="configForm.startGisName" placeholder="请输入模拟位置" class="inner-input" />
            </div>
            <van-button size="small" type="primary" @click="getLocation"
              :disabled="!configForm.startGisName || isLocationCounting" style="width: 110px;">
              {{ !isLocationCounting ? locationButtonText : locationButtonText }}
            </van-button>
          </template>
        </van-field>
        <van-field v-model="configForm.startGisLat" name="startGisLat" label="经度" placeholder="请获取经度" disabled
          :rules="[{ required: true, message: '请获取经度!' }]">
          <template #label>
            &nbsp&nbsp&nbsp&nbsp&nbsp经度
          </template>
        </van-field>
        <van-field v-model="configForm.startGisLon" name="startGisLon" label="纬度" placeholder="请获取纬度" disabled
          :rules="[{ required: true, message: '请获取纬度!' }]">
          <template #label>
            &nbsp&nbsp&nbsp&nbsp&nbsp纬度
          </template>
        </van-field>
      </van-cell-group>

      <!-- 路线选择 -->
      <!-- <van-cell-group inset>
        <van-field>
          <template #label>
            <van-icon name="location" style="margin-right: 5px" />路线选择
          </template>
          <template #input>
            <div style="width: 100%; display: flex; justify-content: flex-end; gap: 8px;">
              <van-button size="small" type="primary" @click="selectJourney">选择行程</van-button>
              <van-button size="small" type="primary" @click="selectCommon">选择常用</van-button>
            </div>
          </template>
        </van-field>

        <div style="margin: 5px auto;"></div>

        <van-field v-model="configForm.selectRoutes" name="typeMode" placeholder="行程同步">
          <template #label>
            <van-button :loading="xcLoading" size="small" type="primary" @click="xcLoad">
              行程同步
            </van-button>
          </template>
          <template #input>
            <div class="sync-status">
              <div class="selected-count">
                已选择{{ selectedJourneyIds.length }}个行程 >
              </div>
            </div>
          </template>
        </van-field>

        <van-field v-model="configForm.selectFrequentRoutes" name="typeMode" placeholder="常用同步">
          <template #label>
            <van-button :loading="cyLoading" size="small" type="primary" @click="cyLoad">
              常用同步
            </van-button>
          </template>
          <template #input>
            <div class="sync-status">
              <div class="selected-count">
                已选择{{ selectedFrequentRouteIds.length }}个常用路线 >
              </div>
            </div>
          </template>
        </van-field> -->

      <!-- 行程选择弹窗 -->
      <!-- <van-popup teleport="body" v-model:show="showJourneyPopup" position="bottom">
          <div class="popup-content">
            <div class="popup-header">
              <span>选择行程</span>
              <van-button type="primary" size="small" @click="confirmJourneySelection">确定</van-button>
            </div>
            <van-checkbox-group v-model="selectedJourneyIds">
              <van-cell-group>
                <van-cell v-for="item in journeyList" :key="item.route_id">
                  <template #title>
                    <van-checkbox :name="item.route_id">
                      <div class="sub-title">{{ item.from_name }}</div>
                      <div class="sub-title">{{ item.to_name }}</div>
                    </van-checkbox>
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </div>
        </van-popup> -->

      <!-- 常用路线选择弹窗 -->
      <!-- <van-popup teleport="body" v-model:show="showCommonPopup" position="bottom">
          <div class="popup-content">
            <div class="popup-header">
              <span>选择常用路线</span>
              <van-button type="primary" size="small" @click="confirmCommonSelection">确定</van-button>
            </div>
            <van-checkbox-group v-model="selectedFrequentRouteIds">
              <van-cell-group>
                <van-cell v-for="item in commonList" :key="item.fixed_route_id">
                  <template #title>
                    <van-checkbox :name="item.fixed_route_id">
                      <div class="sub-title">{{ item.to_name }}</div>
                      <div class="sub-title">{{ item.from_name }}</div>
                    </van-checkbox>
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </div>
        </van-popup>
      </van-cell-group> -->

      <!-- 高速费用 -->
      <van-cell-group inset>
        <van-field v-model="configForm.tollFeeStatus" is-link readonly name="highwayFee" label="高速费用"
          placeholder="请选择费用" @click="showFeePopup = true" :rules="[{ required: true, message: '请选择费用!' }]">
          <template #label>
            <van-icon name="balance-o" style="margin-right: 5px" />高速费用
          </template>
          <template #input>
            <div class="selected-count">
              已选择 - {{ selecttollFeeStatus ? '只接愿意承担高速费【不推荐】' : '接全部订单' }}
            </div>
          </template>
        </van-field>

        <!-- 费用选择弹窗 -->
        <van-popup teleport="body" v-model:show="showFeePopup" position="bottom">
          <div class="popup-content">
            <div class="popup-header">
              <span>选择费用</span>
              <van-button type="primary" size="small" @click="confirmFeeSelection">确定</van-button>
            </div>
            <van-radio-group v-model="selecttollFeeStatus">
              <van-cell-group>
                <van-cell v-for="fee in feeOptions" :key="fee.id">
                  <template #title>
                    <van-radio :name="fee.id">{{ fee.name }}</van-radio>
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </div>
        </van-popup>

        <van-field v-model="configForm.startTime" is-link readonly name="startTime" label="开始时间" placeholder="请选择开始时间"
          @click="showStartTimePicker = true"
          :rules="[{ required: true, message: '请选择开始时间!' }, { validator: validateEndTime, message: '开始时间不能大于结束时间！' }]">
          <template #label>
            <van-icon name="clock-o" style="margin-right: 5px" />开始时间
          </template>
        </van-field>

        <van-field v-model="configForm.endTime" is-link readonly name="endTime" label="结束时间" placeholder="请选择结束时间"
          @click="showEndTimePicker = true"
          :rules="[{ required: true, message: '请选择结束时间!' }, { validator: validateEndTime, message: '开始时间不能大于结束时间！' }]">
          <template #label>
            <van-icon name="clock-o" style="margin-right: 5px" />结束时间
          </template>
        </van-field>

        <!-- 开始时间选择器 -->
        <select-time-pop v-model:modelValue="showStartTimePicker" v-model:timeValue="configForm.startTime"
          :defaultValue="configForm.startTime" />

        <!-- 结束时间选择器 -->
        <select-time-pop v-model:modelValue="showEndTimePicker" v-model:timeValue="configForm.endTime"
          :defaultValue="configForm.endTime" />
      </van-cell-group>

      <!-- 订单金额 -->
      <van-cell-group inset>
        <van-field name="orderAmount" label="订单金额" :rules="[
          { validator: validateOrderAmount, message: orderAmountError }
        ]">
          <template #label>
            <van-icon name="balance-o" style="margin-right: 5px" />订单金额
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.minAmount" type="digit" placeholder="最小金额" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.maxAmount" type="digit" placeholder="最大金额" class="range-input" />
              <span class="range-unit">元</span>
            </div>
          </template>
        </van-field>

        <van-field name="refreshRate" label="刷新频率" :rules="[
          { validator: validateRefreshRate, message: refreshRateError }
        ]">
          <template #label>
            <van-icon name="replay" style="margin-right: 5px" />刷新频率
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.updateIntervalMin" type="digit" placeholder="最小频率" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.updateIntervalMax" type="digit" placeholder="最大频率" class="range-input" />
              <span class="range-unit">毫秒</span>
            </div>
          </template>
        </van-field>

        <van-field name="startDistance" label="起点距离" :rules="[
          { validator: validateStartDistance, message: startDistanceError }
        ]">
          <template #label>
            <van-icon name="location-o" style="margin-right: 5px" />起点距离
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.startGisDistance" type="digit" placeholder="最小距离" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.endGisDistance" type="digit" placeholder="最大距离" class="range-input" />
              <span class="range-unit">公里</span>
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 拼单人数 -->
      <van-cell-group inset>
        <van-field name="peopleRange" label="拼单人数" :rules="[
          { validator: validatePeopleRange, message: peopleRangeError }
        ]">
          <template #label>
            <van-icon name="friends" style="margin-right: 5px" />拼单人数
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.carpoolNumberMin" type="digit" placeholder="最少人数" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.carpoolNumberMax" type="digit" placeholder="最多人数" class="range-input" />
              <van-checkbox v-model="configForm.carpoolNumberChecked" class="range-checkbox" />
            </div>
          </template>
        </van-field>

        <van-field name="enjoyPeopleRange" label="优享人数" :rules="[
          { validator: validateEnjoyPeopleRange, message: enjoyPeopleRangeError }
        ]">
          <template #label>
            <van-icon name="friends" style="margin-right: 5px" />优享人数
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.enjoyNumberMin" type="digit" placeholder="最少人数" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.enjoyNumberMax" type="digit" placeholder="最多人数" class="range-input" />
              <van-checkbox v-model="configForm.enjoyNumberChecked" class="range-checkbox" />
            </div>
          </template>
        </van-field>

        <van-field name="exclusivePeopleRange" label="独享人数" :rules="[
          { validator: validateExclusivePeopleRange, message: exclusivePeopleRangeError }
        ]">
          <template #label>
            <van-icon name="manager" style="margin-right: 5px" />独享人数
          </template>
          <template #input>
            <div class="people-range">
              <van-field v-model="configForm.exclusiveNumberMin" type="digit" placeholder="最少人数" class="range-input" />
              <div class="range-separator">到</div>
              <van-field v-model="configForm.exclusiveNumberMax" type="digit" placeholder="最多人数" class="range-input" />
              <van-checkbox v-model="configForm.exclusiveNumberChecked" class="range-checkbox" />
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 主号刷新和连续抓单 -->
      <van-cell-group inset>
        <van-field name="mainAccountRefresh" label="主号刷新">
          <template #label>
            <van-icon name="manager-o" style="margin-right: 5px" />主号刷新
          </template>
          <template #input>
            <div class="switch-container">
              <span>（主号是否参与刷新）</span>
              <van-switch v-model="configForm.mainRef" size="20" />
            </div>
          </template>
        </van-field>

        <van-field name="continuousGrab" label="连续抓单">
          <template #label>
            <van-icon name="replay" style="margin-right: 5px" />连续抓单
          </template>
          <template #input>
            <div class="switch-container">
              <span>（抓到单子后不停止）</span>
              <van-switch v-model="configForm.always" size="20" />
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 城市过滤 -->
      <van-cell-group inset>
        <van-field v-model="configForm.onlyCity" name="acceptCity" label="只接城市" placeholder="请输入城市，多个用逗号分隔">
          <template #label>
            <van-icon name="location-o" style="margin-right: 5px" />只接城市
          </template>
          <template #input>
            <div class="city-input">
              <van-field v-model="configForm.onlyCity" placeholder="请输入城市，多个用#分隔" class="inner-input" />
            </div>
          </template>
        </van-field>

        <van-field v-model="configForm.notAcceptCity" name="rejectCity" label="不接城市" placeholder="请输入城市，多个用逗号分隔">
          <template #label>
            <van-icon name="close" style="margin-right: 5px" />不接城市
          </template>
          <template #input>
            <div class="city-input">
              <van-field v-model="configForm.notAcceptCity" placeholder="请输入城市，多个用#分隔" class="inner-input" />
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px 10px;">
        <van-button block type="primary" native-type="submit" :disabled="buttonDisabled">
          保存
        </van-button>
      </div>

      <div style="margin: 16px 10px;">
        <van-button block :type="isGrabbing ? 'danger' : 'success'" :disabled="buttonDisabled" @click="toggleGrabOrder"
          class="grab-order-btn">
          <div class="btn-content">
            <van-icon v-if="!(grabInterval)" :name="isGrabbing ? 'pause' : 'play'" class="btn-icon" />
            <span>{{ grabInterval ? crabTime + '再次开始抢单（点击停止）' : (isGrabbing ? '停止抢单' : '开始抢单') }}</span>
          </div>
          <div v-if="isGrabbing" class="grab-animation"></div>
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch, unref, onUnmounted } from 'vue';
import { format, parse } from 'date-fns'
import { useStore } from 'vuex';
import { showNotify, showDialog } from "vant";
import SelectTimePop from '@/components/selectTimePop.vue';
import { routeApi, gisApi, loginApi, frequentRouteApi, orderApi, subTokenApi } from '@/api';
import { StorageUtil } from '@/utils/storage'
import qs from 'qs'
import moment from 'moment'

export default {
  components: {
    SelectTimePop,
  },
  setup() {
    const store = useStore()

    const active = computed(() => store.state.active)

    watch(active, (newValue) => {
      if (newValue === '0') {
        loadConfig()
      }
    })

    const buttonDisabled = ref(false);

    const configForm = reactive({
      // 倒计时时间
      clockTime: null,

      // 模式选择
      selectedTypes: [], // 跨域、市内、行程、常用

      // 位置信息
      startGisName: '', // 模拟位置
      startGisLat: '', // 经度
      startGisLon: '', // 纬度

      // 路线选择
      selectPath: '', // 路线
      selectedJourneys: [], // 选择的行程
      selectedCommons: [], // 选择的常用路线

      // 高速费用
      tollFeeStatus: '', // 选择的费用

      // 时间
      startTime: '', // 开始时间
      endTime: '', // 结束时间

      // 订单金额范围
      minAmount: '',
      maxAmount: '',

      // 刷新频率
      updateIntervalMin: '',
      updateIntervalMax: '',

      // 起点距离
      startGisDistance: '',
      endGisDistance: '',

      // 拼单人数
      carpoolNumberMin: '',
      carpoolNumberMax: '',
      carpoolNumberChecked: false,

      // 独享人数
      exclusiveNumberMin: '',
      exclusiveNumberMax: '',
      exclusiveNumberChecked: false,

      // 优享人数
      enjoyNumberChecked: false,
      enjoyNumberMin: null,
      enjoyNumberMax: null,

      // 主号和连续抓单开关
      mainRef: false,
      always: false,

      // 城市过滤
      onlyCity: '',
      notAcceptCity: '',

      selectRoutes: '', // 存储选中的行程
      selectFrequentRoutes: '', // 存储选中的常用路线
    });


    // 时钟倒计时
    // 倒计时显示
    const countdownDisplay = ref('--')

    // 重置倒计时
    const resetClockTime = () => {
      // 生成符合 yyyy-MM-dd HH:mm:ss 格式的时间字符串
      configForm.clockTime = format(new Date(Date.now() + 60 * 60 * 1000), 'yyyy-MM-dd HH:mm:ss')
      onSubmit()
    }

    // 计算倒计时
    const updateCountdownDisplay = () => {
      if (!configForm.clockTime) {
        countdownDisplay.value = '--'
        return
      }

      try {
        const now = new Date()
        const target = parse(configForm.clockTime, 'yyyy-MM-dd HH:mm:ss', new Date())
        const duration = target - now

        if (duration <= 0) {
          configForm.clockTime = null
          countdownDisplay.value = '已过期'

          // 停止定时器
          if (countdownTimer.value) {
            clearInterval(countdownTimer.value)
            countdownTimer.value = null
          }

          const audio = new Audio(require('../assets/mp3/renlian.mp3'))
          window.currentTimeMusic = audio;
          audio.play().catch(error => {
            console.error('播放音频错误:', error)
          })

          showDialog({
            title: "刷脸过期",
            message: "刷脸过期了噢, 请重新在APP内刷脸!",
          }).then(() => {
            // 停止之前可能正在播放的音频
            if (window.currentTimeMusic) {
              window.currentTimeMusic.pause();
              window.currentTimeMusic.currentTime = 0;
            }
          });

          return
        }

        const hours = Math.floor(duration / (1000 * 60 * 60))
        const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((duration % (1000 * 60)) / 1000)

        countdownDisplay.value = `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
      } catch (error) {
        console.error('时间计算错误:', error)
        countdownDisplay.value = '--'
      }
    }

    // 定时器
    const countdownTimer = ref(null)

    // 卸载时清理定时器
    onUnmounted(() => {
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
      }
    })

    // 表单验证方法
    const validateOrderAmount = (val) => {
      const min = parseFloat(configForm.minAmount);
      const max = parseFloat(configForm.maxAmount);
      return min >= 0 && max > min && max <= 99999;
    };

    const validateRefreshRate = (val) => {
      const min = parseFloat(configForm.updateIntervalMin);
      const max = parseFloat(configForm.updateIntervalMax);
      return min >= 100 && max > min && max <= 999999;
    };

    const validateStartDistance = (val) => {
      const min = parseFloat(configForm.startGisDistance);
      const max = parseFloat(configForm.endGisDistance);
      return min >= 9 && max > min && max <= 99999;
    };

    const validatePeopleRange = (val) => {
      const min = parseFloat(configForm.carpoolNumberMin);
      const max = parseFloat(configForm.carpoolNumberMax);
      return min >= 1 && max > min && max <= 99999;
    };

    const validateExclusivePeopleRange = (val) => {
      const min = parseFloat(configForm.exclusiveNumberMin);
      const max = parseFloat(configForm.exclusiveNumberMax);
      return min >= 1 && max > min && max <= 99999;
    };

    const validateAcceptCity = (val) => {
      return configForm.onlyCity.trim() !== '';
    };

    const validateRejectCity = (val) => {
      return configForm.notAcceptCity.trim() !== '';
    };

    // 结束时间不能大于开始时间
    const validateEndTime = () => {
      // 确保开始时间和结束时间都已填写
      if (!configForm.startTime || !configForm.endTime) {
        return false; // 验证失败
      }

      // 使用 moment 进行时间比较
      const startTime = moment(configForm.startTime);
      const endTime = moment(configForm.endTime);

      // 检查结束时间是否晚于开始时间
      // 如果结束时间早于或等于开始时间，返回 true（表示验证失败）
      if (endTime.isSameOrBefore(startTime)) {
        return false; // 验证失败
      }

      // // 检查时间跨度是否过长（例如，不超过7天）
      // const maxDuration = moment.duration(7, 'days');
      // if (endTime.diff(startTime, 'days') > 7) {
      //   return true; // 验证失败
      // }

      return true; // 验证通过
    };

    // 错误消息
    const orderAmountError = ref('订单金额 0 到 99999');
    const refreshRateError = ref('刷新频率 100 到 99999');
    const startDistanceError = ref('起点距离 9 到 99999');
    const peopleRangeError = ref('拼单人数 1 到 99999');
    const exclusivePeopleRangeError = ref('独享人数 1 到 99999');
    const acceptCityError = ref('请输入接单城市');
    const rejectCityError = ref('请输入拒单城市');

    // 提交方法
    const onSubmit = (flag = true) => {
      return new Promise((r, rj) => {
        buttonDisabled.value = true;
        setTimeout(() => {
          buttonDisabled.value = false;
        }, 3000);

        if (!configForm.token) {
          showNotify({ type: 'danger', message: 'token为空!' });
          return;
        }
        if (!configForm.phoneNumber) {
          showNotify({ type: 'danger', message: '接单账号为空!' });
          return;
        }

        // 准备提交的数据
        const submitData = { ...configForm };

        // 转换数据格式
        submitData.selectedTypes = submitData.selectedTypes.join(',');
        submitData.selectedJourneys = JSON.parse(submitData.selectRoutes || '[]').map(i => i.route_id);
        submitData.selectedCommons = JSON.parse(submitData.selectFrequentRoutes || '[]').map(i => i.fixed_route_id);
        submitData.selectedCommons = submitData.selectedCommons.join(',');

        // 调用API提交
        loginApi.updateUserConfig(submitData)
          .then(response => {
            loadConfig(flag)
            if (flag) {
              showNotify({ type: 'success', message: '配置保存成功' });
            }
          })
          .catch(error => {
            showNotify({ type: 'danger', message: error.message || '配置保存失败' });
          }).finally(() => {
            r()
          })
      })
    };

    const showJourneyPopup = ref(false);
    const showCommonPopup = ref(false);
    const journeyList = ref([]);
    const commonList = ref([]);

    const selecttollFeeStatus = ref([]);
    const feeOptions = [
      { id: false, name: '接全部订单' },
      { id: true, name: '只接愿意承担高速费【不推荐】' },
    ];

    const showFeePopup = ref(false);
    const startTime = ref('');
    const endTime = ref('');
    const showStartTimePicker = ref(false);
    const showEndTimePicker = ref(false);

    // 获取经纬度
    const isLocationCounting = ref(false);
    const locationButtonText = ref('获取经纬度');
    const locationCountdown = ref(0);

    const getLocation = () => {
      if (isLocationCounting.value) return;

      isLocationCounting.value = true;
      locationCountdown.value = 10;

      if (!configForm.startGisName) {
        showNotify({ type: 'danger', message: '请输入地点名称' });
        return;
      }

      const timer = setInterval(() => {
        locationCountdown.value--;
        locationButtonText.value = locationCountdown.value + 's';
        
        if (locationCountdown.value <= 0) {
          clearInterval(timer);
          isLocationCounting.value = false;
          locationButtonText.value = '获取经纬度';
        }
      }, 1000);

      // 调用API获取经纬度
      const params = qs.stringify({
        startGisName: configForm.startGisName
      });

      gisApi.getLonLat(params)
        .then(response => {
          configForm.startGisLat = response.lat;
          configForm.startGisLon = response.lon;
          showNotify({ type: 'success', message: '经纬度获取成功' });
        })
        .catch(error => {
          console.error('获取经纬度失败', error);
          showNotify({ type: 'danger', message: '获取经纬度失败' });
        });
    };

    const selectedJourneyIds = ref([]);

    // 行程
    const confirmJourneySelection = async () => {
      // 将选中的行程转换为指定格式
      console.log('将选中的行程', selectedJourneyIds.value);

      const selectedRoutes = selectedJourneyIds.value.map(id => ({
        route_id: id
      }));

      configForm.selectRoutes = JSON.stringify(selectedRoutes);

      const cardKey = StorageUtil.getCardKey();

      const param = qs.stringify({ cardKey, selectRoutes: configForm.selectRoutes });

      await routeApi.saveRoute(param)

      showJourneyPopup.value = false;
    };

    const selectedFrequentRouteIds = ref([]);

    // 常用路线
    const confirmCommonSelection = async () => {
      // 将选中的路线转换为指定格式
      console.log('将选中的路线', selectedFrequentRouteIds.value);

      const selectedFrequentRoutes = selectedFrequentRouteIds.value.map(id => ({
        fixed_route_id: id
      }));
      configForm.selectFrequentRoutes = JSON.stringify(selectedFrequentRoutes);

      const cardKey = StorageUtil.getCardKey();

      const param = qs.stringify({ cardKey, selectFrequentRoutes: configForm.selectFrequentRoutes });

      await frequentRouteApi.saveFrequentRoute(param)
      showCommonPopup.value = false;
    };

    const confirmFeeSelection = (val) => {
      console.log('将选中的费用', selecttollFeeStatus.value);

      configForm.tollFeeStatus = selecttollFeeStatus.value
      showFeePopup.value = false;
    };

    // 选择行程
    const selectJourney = async () => {
      await fetchJourneyList();
      const old_selectedJourneys = configForm.selectedJourneys;
      const new_selectedJourneys = old_selectedJourneys.filter(id =>
        journeyList.value.some(item => item.route_id === id)
      );
      selectedJourneyIds.value = new_selectedJourneys;
      showJourneyPopup.value = true
    };

    // 选择常用
    const selectCommon = async () => {
      await fetchCommonList();
      const old_selectedCommons = configForm.selectedCommons;
      const new_selectedCommons = old_selectedCommons.filter(id =>
        commonList.value.some(item => item.fixed_route_id === id)
      );
      selectedFrequentRouteIds.value = new_selectedCommons;
      showCommonPopup.value = true
    };

    // 抢单状态
    const isGrabbing = ref(false);
    let grabInterval = null;

    const logInterval = computed(() => store.state.logInterval)
    watch(logInterval, (newValue) => {
      if (!newValue) {
        isGrabbing.value = false
      }
    })

    // 验证
    const validateJourney = () => {
      const selectedTypes = unref(configForm.selectedTypes);
      if (selectedTypes.includes('行程')) {
        return Array.isArray(selectedJourneyIds.value) && selectedJourneyIds.value.length === 0
      } else {
        return false
      }
    }
    // 验证
    const validateCommon = () => {
      const selectedTypes = unref(configForm.selectedTypes);

      if (selectedTypes.includes('常用')) {
        return Array.isArray(selectedFrequentRouteIds.value) && selectedFrequentRouteIds.value.length === 0
      } else {
        return false
      }
    }

    const formRef = ref(null)

    // 切换抢单状态
    const toggleGrabOrder = async () => {
      // 如果有自动抢单，就先关闭抢单
      if (store.state.grabInterval) {
        store.dispatch('clearCrabTime')
        return
      }

      await onSubmit(false)
      formRef.value.validate().then(async (res) => {

        // if (validateCommon()) {
        //   showNotify({ type: 'danger', message: '请选择常用路线!' });
        //   return;
        // }
        // if (validateJourney()) {
        //   showNotify({ type: 'danger', message: '请选择行程!' });
        //   return;
        // }

        buttonDisabled.value = true;
        setTimeout(() => {
          buttonDisabled.value = false;
        }, 3000);

        try {
          isGrabbing.value = !isGrabbing.value;

          if (isGrabbing.value) {
            const submitData = { ...configForm };

            // 转换数据格式
            submitData.selectedTypes = submitData.selectedTypes.join(',');
            submitData.selectedJourneys = JSON.parse(submitData.selectRoutes || '[]').map(i => i.route_id);
            submitData.selectedCommons = JSON.parse(submitData.selectFrequentRoutes || '[]').map(i => i.fixed_route_id);
            submitData.selectedCommons = submitData.selectedCommons.join(',');

            // 开始抢单
            store.dispatch('clearLogs')
            const res = await orderApi.startGrabOrder(submitData)

            // 开始全局日志轮询
            store.dispatch('startLogPolling')

            // 弹窗
            showNotify({
              type: 'success',
              message: res,
              duration: 2000
            });
          } else {
            // 停止抢单
            const res = await orderApi.stopGrabOrder({
              cardKey: StorageUtil.getCardKey()
            })

            // 停止全局日志轮询
            store.dispatch('stopLogPolling2')

            // 停止之前可能正在播放的音频
            if (window.currentAudio) {
              window.currentAudio.pause();
              window.currentAudio.currentTime = 0;
            }

            showNotify({
              type: 'success',
              message: res,
              duration: 2000
            });
          }

          console.log(isGrabbing.value);

        } catch (error) {
          console.log(error)
          isGrabbing.value = false;
          store.dispatch('stopLogPolling')
          showNotify({
            type: 'danger',
            message: '操作失败: ' + error.message,
            duration: 2000
          });
        }
      }).catch(e => {
        console.log(e);
      })
    };

    // 回显数据的方法
    const loadConfig = (flag = true, type) => {

      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      loginApi.login(cardKey)
        .then(response => {

          if (type === 'mounted') {
            if (!response.phoneNumber || !response.token) {
              store.commit('setActive', '1')

              showNotify({
                type: 'warning',
                message: '无主号手机号或token为空！'
              });
            }
          }

          if (response.state) {
            // 调用统一的日志轮询处理方法
            handleLogPolling(response.state)
          }

          // 使用解构赋值，确保不会意外覆盖其他属性
          Object.assign(configForm, {
            ...response,
            selectedTypes: response.selectedTypes ? response.selectedTypes.split(',') : [],
            selectedJourneys: response.selectRoutes ? JSON.parse(response.selectRoutes).map(i => i.route_id) : [], // 将字符串转换为数组
            selectedCommons: response.selectFrequentRoutes ? JSON.parse(response.selectFrequentRoutes).map(i => i.fixed_route_id) : [],
          });

          selectedJourneyIds.value = [];
          selectedFrequentRouteIds.value = [];
          // 将选中的行程和常用路线回显
          selectedJourneyIds.value = configForm.selectedJourneys;
          // 将选中的行程和常用路线回显
          selectedFrequentRouteIds.value = configForm.selectedCommons;
          selecttollFeeStatus.value = configForm.tollFeeStatus
          if (flag) isGrabbing.value = configForm.state

          // 下面数据是初始化
          // 如果时间是空赋值为当天时间 0点 到 23点
          configForm.startTime = configForm.startTime || moment().format('YYYY-MM-DD HH:mm:ss');
          configForm.endTime = configForm.endTime || moment().add(1, 'days').format('YYYY-MM-DD 23:59:59');

          if (flag) {
            showNotify({ type: 'success', message: '配置加载成功' });
          }

          if (!countdownTimer.value) {
            // 更新倒计时
            countdownTimer.value = setInterval(updateCountdownDisplay, 1000)
          }
        })
        .catch(error => {
          console.error(error);
          showNotify({ type: 'danger', message: '配置加载失败' });
        });
    };

    // 统一的日志轮询处理方法
    const handleLogPolling = (isGrabbing) => {
      if (isGrabbing) {
        // 开始全局日志轮询
        store.dispatch('startLogPolling')
      }
    }

    // 获取行程列表
    const fetchJourneyList = async () => {
      try {
        const cardKey = StorageUtil.getCardKey();
        const token = StorageUtil.getToken();
        const params = qs.stringify({
          token: token,
          cardKey: cardKey
        });
        // 调用API获取行程列表
        const response = await routeApi.getRouteList(params);
        journeyList.value = response || [];
      } catch (error) {
        console.error('获取行程列表失败', error);
        showNotify({ type: 'danger', message: '获取行程列表失败' });
      }
    };

    // 获取常用路线列表
    const fetchCommonList = async () => {
      try {
        const cardKey = StorageUtil.getCardKey();
        const token = StorageUtil.getToken();
        const params = qs.stringify({
          token: token,
          cardKey: cardKey
        });
        const response = await frequentRouteApi.getFrequentRouteList(params);
        commonList.value = response || [];
      } catch (error) {
        console.error('获取常用路线列表失败', error);
        showNotify({ type: 'danger', message: '获取常用路线列表失败' });
      }
    };

    // 在组件挂载时加载配置
    onMounted(async () => {
      loadConfig(true, 'mounted')
    });

    const xcLoading = ref(false)
    const xcLoad = () => {
      if (!configForm.token) {
        showNotify({ type: 'warning', message: '无主号token, 请填写主号！' });
        return
      }

      if (!configForm.subTokens) {
        showNotify({ type: 'warning', message: '小号不存在！' });
        return
      }

      xcLoading.value = true

      const params = qs.stringify({
        token: configForm.token,
        startGisLon: configForm.startGisLon,
        startGisLat: configForm.startGisLat,
        subTokens: configForm.subTokens
      });
      subTokenApi.synRoutes(params).then((res) => {
        showNotify({ type: 'success', message: res });
      }).finally(() => {
        xcLoading.value = false
      }).catch((error) => {
        console.error('同步小号路线失败', error);
        showNotify({ type: 'danger', message: '同步小号路线失败' });
      })
    }

    const cyLoading = ref(false)
    const cyLoad = () => {
      if (!configForm.token) {
        showNotify({ type: 'warning', message: '无主号token, 请填写主号！' });
        return
      }

      if (!configForm.subTokens) {
        showNotify({ type: 'warning', message: '小号不存在！' });
        return
      }

      cyLoading.value = true
      const params = qs.stringify({
        token: configForm.token,
        startGisLon: configForm.startGisLon,
        startGisLat: configForm.startGisLat,
        subTokens: configForm.subTokens
      });
      subTokenApi.synFrequentRoute(params).then((res) => {
        showNotify({ type: 'success', message: res });
      }).finally(() => {
        cyLoading.value = false
      }).catch((error) => {
        console.error('同步小号常用路线失败', error);
        showNotify({ type: 'danger', message: '同步小号常用路线失败' });
      })
    }

    return {
      isLocationCounting,
      locationButtonText,
      locationCountdown,
      validateJourney,
      validateCommon,
      validateEndTime,
      xcLoading,
      xcLoad,
      cyLoading,
      cyLoad,
      selecttollFeeStatus,
      configForm,
      countdownDisplay,
      resetClockTime,
      validateOrderAmount,
      validateRefreshRate,
      validateStartDistance,
      validatePeopleRange,
      validateExclusivePeopleRange,
      validateAcceptCity,
      validateRejectCity,
      orderAmountError,
      refreshRateError,
      startDistanceError,
      peopleRangeError,
      exclusivePeopleRangeError,
      acceptCityError,
      rejectCityError,
      onSubmit,
      showJourneyPopup,
      showCommonPopup,
      journeyList,
      commonList,
      feeOptions,
      showFeePopup,
      startTime,
      endTime,
      showStartTimePicker,
      showEndTimePicker,
      getLocation,
      confirmJourneySelection,
      confirmCommonSelection,
      confirmFeeSelection,
      selectJourney,
      selectCommon,
      selectedJourneyIds,
      selectedFrequentRouteIds,
      isGrabbing,
      toggleGrabOrder,
      formRef,
      buttonDisabled,
      grabInterval: computed(() => store.state.grabInterval),
      crabTime: computed(() => store.state.updateTime)
    };
  },
};
</script>

<style lang="less" scoped>
// 弹窗 start
.van-popup--bottom {
  width: 100% !important;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  padding: 8px 20px;
}

.popup-content {
  min-height: 300px;
}

// 弹窗 end

.config {
  padding: 0;

  .van-checkbox--horizontal {
    margin-bottom: 3px;
  }

  .sync-info {
    padding: 0 16px;

    .sync-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      color: #666;
      font-size: 14px;
    }

    .selected-info {
      color: #0053D9;
      font-size: 14px;
      margin-top: 12px;
    }
  }

  .sync-status {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .sync-item {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 14px;
    }

    .selected-count {
      font-size: 14px;
    }
  }

  .popup-content {
    padding: 16px;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      span {
        font-size: 16px;
        font-weight: 500;
      }
    }

    :deep(.van-checkbox-group) {
      margin: 30px 0;
    }
  }

  .people-range {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 8px;

    .range-input {
      flex: 1;
      padding: 0;
      background: transparent;

      :deep(.van-field__body) {
        padding-right: 0;
      }

      :deep(.van-cell) {
        padding: 0;
        background: transparent;

        &::after {
          display: none;
        }
      }
    }

    .range-separator {
      padding: 0 8px;
      color: #969799;
    }

    .range-checkbox {
      margin-left: 8px;
    }

    .range-unit {
      margin-left: 8px;
      color: #969799;
    }
  }

  .location-input {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 8px;

    .inner-input {
      flex: 1;
      padding: 0;
      background: transparent;

      :deep(.van-field__body) {
        padding-right: 0;
      }

      :deep(.van-field__control) {
        border: none;
      }

      :deep(.van-cell) {
        padding: 0;
        background: transparent;

        &::after {
          display: none;
        }
      }
    }
  }

  /deep/.van-cell-group {
    margin: 0 auto;
    margin-top: 20px;
    border-radius: 3px;
    width: 94%;
  }

  /deep/.van-cell-group:first-child {
    margin-top: 0;
  }

  /deep/.van-button--primary {
    color: #fff;
    background: #0053D9;
    border-color: #0053D9;
  }

  /deep/.van-checkbox__icon--checked .van-icon {
    background-color: #0053D9;
    border-color: #0053D9;
  }

  /deep/.van-checkbox--horizontal {
    margin-right: 7px;
  }

  .switch-container {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  .city-input {
    display: flex;
    flex-direction: column;
    width: 100%;
    gap: 8px;

    .city-desc {
      color: #969799;
      font-size: 14px;
    }

    .inner-input {
      padding: 0;
      background: transparent;

      :deep(.van-field__body) {
        padding-right: 0;
      }

      :deep(.van-cell) {
        padding: 0;
        background: transparent;

        &::after {
          display: none;
        }
      }
    }
  }

  .grab-order-btn {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    height: 50px;

    .btn-content {
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      z-index: 10;
    }

    .btn-icon {
      margin-right: 10px;
      font-size: 20px;
    }
  }

  .grab-animation {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg,
        rgba(77, 255, 79, 0.2) 0%,
        rgba(77, 255, 79, 0.5) 50%,
        rgba(77, 255, 79, 0.2) 100%);
    background-size: 200% 100%;
    animation: grabbing-pulse 1.5s infinite linear;
    z-index: 5;
  }

  @keyframes grabbing-pulse {
    0% {
      background-position: -200% 0;
    }

    100% {
      background-position: 200% 0;
    }
  }
}

.sub-title {
  text-align: left;
}

.clock-time-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.clock-time-display {
  font-size: 16px;
  color: #323233;
  font-weight: 500;
}

.reset-button {
  font-size: 12px;
  padding: 4px 8px;
  color: #fff;
}

.van-cell {
  align-items: center;
}
</style>
